local blaze = require "blaze"
local gamelib = require "club.threecard.gamelib"
local app = require "app"
local EntityDef = require "KBE.EntityDef"

local entity_defs = {} -- <class_name, entity>
local class_map = {} -- <class_name, package>

local M = setmetatable({}, { __index = blaze.kbe })

local function class_loader(script_module)
    local name = script_module.name
    local package = class_map[name]

    local ok1, result1 = pcall(require, string.format("%s.entities.%s", package, name))
    if ok1 then
        return result1
    end
    local ok2, result2 = pcall(require, string.format("%s.entities.components.%s", package, name))
    if ok2 then
        return result2
    end
    error(string.format("can't load module class=%s package=%s\nresult1=%s\nresult2=%s", name, package, result1, result2))
end

function M.init(app)
    M.app = app
    M.register("Seat", "club.threecard.gamelib")
    M.register("Chat", "club.threecard.gamelib")
end

function M.release()
    for class_name, sm in pairs(entity_defs) do
        sm:unload_class()
    end
end

function M.register(class_name, package)
    package = package or app.store.game.state.package
    local entity_def = EntityDef.getOrCreateModule(class_name)
    entity_def.class = nil -- 覆盖掉原来的实现
    entity_def.class_loader = class_loader
    entity_defs[class_name] = entity_def
    class_map[class_name] = package
end

return M